import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';

// class MyCustomScrollBehavior extends MaterialScrollBehavior {
//   // Override behavior methods and getters like dragDevices
//   @override
//   Set<PointerDeviceKind> get dragDevices => {
//         PointerDeviceKind.touch,
//         PointerDeviceKind.mouse,
//         // etc.
//       };
// }

// class ScrolledView extends StatelessWidget {
//   final Widget child;

//   final double thickness;
//   final bool showScrollbar;
//   final bool canDragByMouse;

//   final ScrollController _vController;
//   final ScrollController _hController;

//   ScrolledView(
//       {required this.child,
//       ScrollController? vController,
//       ScrollController? hController,
//       this.thickness = 6,
//       this.showScrollbar = true,
//       this.canDragByMouse = true,
//       super.key})
//       : _vController = vController ?? ScrollController(),
//         _hController = hController ?? ScrollController();

//   // Use LayoutBuilder to auto fit child widget to match parent's width and height
//   Widget scrollFrame() => LayoutBuilder(
//         builder: (context, constraint) => Scrollbar(
//           controller: _vController,
//           thickness: thickness,
//           trackVisibility: showScrollbar,
//           thumbVisibility: showScrollbar,
//           child: Scrollbar(
//             controller: _hController,
//             thickness: thickness,
//             trackVisibility: showScrollbar,
//             thumbVisibility: showScrollbar,
//             notificationPredicate: (notif) => notif.depth == 1,
//             child: SingleChildScrollView(
//               scrollDirection: Axis.vertical,
//               controller: _vController,
//               child: SingleChildScrollView(
//                 scrollDirection: Axis.horizontal,
//                 controller: _hController,
//                 child: ConstrainedBox(
//                     constraints: BoxConstraints(
//                         minWidth: constraint.maxWidth,
//                         minHeight: constraint.maxHeight),
//                     child: child),
//               ),
//             ),
//           ),
//         ),
//       );

//   @override
//   Widget build(BuildContext context) => canDragByMouse
//       ? ScrollConfiguration(
//           behavior: MyCustomScrollBehavior(), child: scrollFrame())
//       : scrollFrame();
// }

// /// * [HoveredText] applied a orange color bottom line when hover the text
// class HoveredText extends StatefulWidget {
//   final String text;
//   final Color textColor;
//   final Function? tapFunc;

//   const HoveredText({
//     super.key,
//     required this.text,
//     required this.textColor,
//     this.tapFunc,
//   });

//   @override
//   State<HoveredText> createState() => _HoveredText2State();
// }

// class _HoveredText2State extends State<HoveredText> {
//   bool _hovered = false;
//   final GlobalKey _textKey = GlobalKey();

//   double get _textWidth {
//     final RenderBox textBox =
//         _textKey.currentContext?.findRenderObject() as RenderBox;
//     return textBox.size.width;
//   }

//   @override
//   Widget build(BuildContext context) {
//     return MouseRegion(
//       onHover: (_) => setState(() => _hovered = true),
//       onExit: (_) => setState(() => _hovered = false),
//       child: GestureDetector(
//         onTap: () => widget.tapFunc?.call(),
//         child: Stack(
//           alignment: Alignment.bottomCenter,
//           children: [
//             Padding(
//               padding: const EdgeInsets.only(bottom: 4),
//               child: Text(
//                 widget.text,
//                 key: _textKey, // 添加 key 用于获取文本宽度
//                 style: TextStyle(
//                   color: widget.textColor,
//                   fontWeight: _hovered ? FontWeight.w700 : FontWeight.w500,
//                 ),
//               ),
//             ),
//             AnimatedContainer(
//                 duration: const Duration(milliseconds: 300),
//                 curve: Curves.easeInOut,
//                 width: _hovered ? _textWidth : 0, // 使用实际文本宽度
//                 height: 2,
//                 color: Colors.orangeAccent),
//           ],
//         ),
//       ),
//     );
//   }
// }

// class DropDownBtn extends StatefulWidget {
//   final List<String> dropDownBtnList;

//   const DropDownBtn({required this.dropDownBtnList, super.key});

//   @override
//   State<DropDownBtn> createState() => _DropDownBtnState();
// }

// class _DropDownBtnState extends State<DropDownBtn> {
//   String? _selectedValue;

//   @override
//   void initState() {
//     super.initState();
//     _selectedValue = widget.dropDownBtnList.first;
//   }

//   @override
//   Widget build(BuildContext context) {
//     return DropdownButton<String>(
//       icon: const Icon(Icons.arrow_drop_down, color: Colors.white, size: 32),
//       dropdownColor: Colors.deepOrange.shade50,
//       value: _selectedValue,
//       items: widget.dropDownBtnList.map((e) {
//         return DropdownMenuItem<String>(
//           value: e,
//           child: Text(e,
//               style: const TextStyle(
//                 color: Colors.black,
//                 fontWeight: FontWeight.w500,
//               )),
//         );
//       }).toList(),
//       onChanged: (val) {
//         setState(() {
//           _selectedValue = val;
//         });
//       },
//     );
//   }
// }

// /// * It split name into name and extension;
// /// * Valid cases
// /// testSplitFilename('file.txt', ('file', '.txt'));
// /// testSplitFilename('.hidden', ('', '.hidden')); // Empty name allowed
// /// testSplitFilename('..config', ('.', '.config')); // Dots in name allowed
// /// testSplitFilename('name.with.dots.ext', ('name.with.dots', '.ext'));
// /// testSplitFilename('..double.dot', ('..double', '.dot'));
// /// * Invalid case
// /// testSplitFilename('no_extension', null);
// /// testSplitFilename('invalid.', null); // Ends with dot
// /// testSplitFilename('.', null); // Just a dot
// /// testSplitFilename('', null); // Empty
// /// testSplitFilename(null, null); // Null
// (String name, String extension)? splitFilename(String? fullFilename) {
//   if (fullFilename == null || fullFilename.isEmpty) return null;

//   final lastDotIndex = fullFilename.lastIndexOf('.');

//   if (lastDotIndex == -1 || lastDotIndex == fullFilename.length - 1) {
//     return null;
//   }

//   return (
//     fullFilename.substring(0, lastDotIndex), // Accept anything before dot
//     fullFilename.substring(lastDotIndex) // Must have content after dot
//   );
// }

// 计算时间差
String formatUSTimeDiff(double utcTimestamp) {
  // 1. UTC 时间戳转 DateTime（UTC）
  DateTime utcTime = DateTime.fromMillisecondsSinceEpoch(
    (utcTimestamp * 1000).toInt(),
    isUtc: true,
  );

  // 2. 转为本地时区时间
  DateTime localTime = utcTime.toLocal();

  // 3. 当前本地时间
  DateTime nowLocal = DateTime.now();

  // 4. 计算差值
  final diff = localTime.difference(nowLocal);

  if (diff.inMinutes < 60) {
    return '${diff.inMinutes}m';
  } else if (diff.inHours < 24) {
    return '${diff.inHours}h';
  } else {
    return '${diff.inDays}days';
  }
}

String convertToUSTime(double east8Timestamp, {bool showTime = false}) {
  // 时间戳是秒，先转为 DateTime（东八区）
  DateTime beijingTime = DateTime.fromMillisecondsSinceEpoch(
    (east8Timestamp * 1000).toInt(),
    isUtc: true,
  ).add(const Duration(hours: 8)); // 东八区

  // 转为美西时间（PST，UTC-8）
  DateTime usTime = beijingTime.subtract(const Duration(hours: 16));

  // 返回年月日或年月日时分秒
  if (showTime) {
    return "${usTime.year.toString().padLeft(4, '0')}-${usTime.month.toString().padLeft(2, '0')}-${usTime.day.toString().padLeft(2, '0')} ${usTime.hour.toString().padLeft(2, '0')}:${usTime.minute.toString().padLeft(2, '0')}:${usTime.second.toString().padLeft(2, '0')}";
  } else {
    return "${usTime.year.toString().padLeft(4, '0')}-${usTime.month.toString().padLeft(2, '0')}-${usTime.day.toString().padLeft(2, '0')}";
  }
}

/// 返回 true 表示东八区时间 > 本地当前时间
bool diffDateStartNow(int east8Timestamp) {
  // 获取本地当前时间戳（毫秒）
  int localNow = (DateTime.now().millisecondsSinceEpoch / 1000).toInt();

  // 直接比较即可
  return east8Timestamp < localNow;
}
